module.exports = {
	com_set_config() {
		let _config = null;
		// #ifdef APP-PLUS
		_config = getApp().globalData.app_init;
		// #endif
		// #ifndef APP-PLUS
		_config = this;
		// #endif
		return _config;
	},

	com_getonce(callback) {
		let _this = this;
		if (!_this.change_var.once_req) {
			callback && callback();
			_this.change_var.once_req = true;
		}
	},
	async com_upload_old(v) {
		let _this = this;
		let { url = '/base/upload', type, path, callback } = v;
		// console.log(path, 'path');
		let str = await _this.pathToBase64_fun(path);
		let _back = await _this.com_getdata({
			url,
			data_handle_on: false,
			data: {
				type,
				str,
			},
			header: { 'Content-Type': 'application/json' },
			timeout: 30000,
		});
		// console.log(_back, 'com_upload');
		return _back;
	},
	com_upload(config) {
		let _this = this;
		let { url = '/base/upload_file', type, path, progress = false } = config;
		let _config = _this.com_set_config();
		let req_url = _config.apiUrl + _config.apiFilename + url;
		if (type) {
			req_url += `?type=${type}`;
		}
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: req_url,
				filePath: path,
				name: 'file',
				timeout: _config.timeout,

				success(res) {
					let data = JSON.parse(res.data);
					resolve(data);
				},
				fail(res) {
					resolve(false);
				},
			}).onProgressUpdate(res => {
				progress && progress(res);
			});
		});
	},

	com_getdata(e) {
		let {
			url,
			data = {},
			data_handle_on = true, //作加密处理
			method = 'POST',
			data_fun,
			fail_fun,
			complete_fun,
			id_name = '',
			mode = 'default',
			timeout = 0,
			header = false,
			show_log = false,
			show_data = false,
		} = e;
		let _this = this;

		let _config = this.com_set_config();

		if (id_name) {
			let user_id = uni.getStorageSync('userid') || '';
			data[id_name] = user_id;
		}

		if (data_handle_on) {
			data = _this.data_handle(data);
		}

		if (_this.show_log || show_log) {
			console.log(`com_getdata:${JSON.stringify(data)}---${JSON.stringify(url)}`);
		}

		let req_url = _config.apiUrl + _config.apiFilename + url;

		if (mode == 'pay') {
			// 支付接口
			req_url = _config.apiUrl + url;
		} else if (mode == 'network') {
			//  外链
			req_url = url;
		}
		if (header) {
			header = _this.header_handle(header);
		} else {
			header = _this.header_handle(_config.headers);
		}
		if (timeout == 0) {
			timeout = _config.timeout;
		}
		// console.log(header);
		return new Promise((resolve, reject) => {
			uni.request({
				header,
				url: req_url,
				data,
				method,
				timeout,
				success(res) {
					let data = res.data;
					// #ifdef APP
					data = _this.com_init_data(data);
					// #endif
					if (_this.show_data || show_data) {
						console.log(data);
					}
					if (data_fun) {
						data_fun && data_fun(data);
					}
					resolve(data);
					_this.$forceUpdate();
				},
				fail(res) {
					if (fail_fun) {
						fail_fun && fail_fun();
					}
					resolve(false);
				},
				complete() {
					if (complete_fun) {
						complete_fun();
					}
				},
			});
		});
	},

	com_getlist(e) {
		let {
			url,
			data = this.page_form,
			load_name = 'loadingstatus',
			form_name = 'page_form',
			export_name = 'page_list',
			id_name = '',
			before_req_fun, //请求前
			before_fun, //处理前
			callback, //处理后
			fail_fun, //失败回调
			complete_fun, //最后回调
			data_handle_on = true, // 作加密处理
			method = 'POST',
			_datakey = 'data',
		} = e;
		let _this = this;
		let _config = this.com_set_config();
		// console.log(_this[load_name], 'com_getlist--loadingstatus');
		if (_this[load_name] == 1 || _this[load_name] == 2) return;
		_this[load_name] = 1;
		if (id_name) {
			let user_id = uni.getStorageSync('userid') || '';
			data[id_name] = user_id;
		}

		if (data_handle_on) {
			data = _this.data_handle(data);
		}
		before_req_fun && before_req_fun();
		return new Promise((resolve, reject) => {
			uni.request({
				header: _this.header_handle(_config.headers),
				data,
				method,
				timeout: _config.timeout,
				url: _config.apiUrl + _config.apiFilename + url,
				success(res) {
					let _resdata = res.data;
					// let total = _this[form_name].count = data.count;
					let back_count = _this.objJudge(_resdata[_datakey]) ? _resdata[_datakey].length : 0;

					// if (_this.objJudge(_resdata[_datakey])) {
					if (_resdata.state == 1) {
						before_fun && before_fun(_resdata);

						if (_this[form_name].page == 1) {
							_this[export_name] = _resdata[_datakey];
						} else {
							_resdata[_datakey].forEach(element => {
								_this[export_name].push(element);
							});
						}
						if (_this[form_name].limit <= back_count) {
							_this[load_name] = 0;
							_this[form_name].page = parseInt(_this[form_name].page) + 1;
						} else {
							setTimeout(() => {
								_this[load_name] = 2;
							}, 300);
						}

						callback && callback(_this[export_name]);
						resolve(true);
					} else {
						setTimeout(() => {
							_this[load_name] = 2;
						}, 300);
					}
				},
				fail: res => {
					if (fail_fun) {
						fail_fun();
					} else {
					}
					resolve(false);
				},
				complete() {
					if (complete_fun) {
						complete_fun();
					} else {
					}
				},
			});
		});
	},
	//  loding -> 成功 失败
	//  成功带不带icon  失败带不带icon
	// 通用加载
	com_loading(e) {
		/* status 1 开始 0 直接隐藏 2成功 */
		let {
			k = 'nextreq',
			title = '请稍候...',
			mask = true,
			time = 1000,
			hide_time = 0,
			duration = 2000,
			icon = 'success',
			type = 'loading',
			status = 1,
			throttle = false, //默认关闭节流阀
			throttle_tips = false,
			loading_log = false,
			callback = false, // 动作结束后的回调
			timeout_limit = 5000, //超过多久自动触发超时回调
			timeout_callback = false,
		} = e;
		let _this = this;
		let _f = _this[k];
		if (loading_log) {
			console.log(e);
			console.log('com_loading变量状态----------------------------------', _f, ' 状态', status);
		}
		if (throttle) {
			if (status == 1) {
				if (!_f) {
					if (throttle_tips) {
						uni.showToast({
							title: '请稍等片刻再试~',
							duration,
							icon: 'none',
						});
					}
					// 节流阀
					return false;
				}
				_this[k] = false;
			} else {
				// 高频操作使用 time 限制
				if (time > 0) {
					setTimeout(() => {
						_this[k] = true;
					}, time);
				} else {
					_this[k] = true;
				}
			}
		}
		switch (status) {
			case 0:
				// 0 直接隐藏
				if (hide_time > 0) {
					setTimeout(() => {
						callback && callback();
						uni.hideLoading();
					}, hide_time);
				} else {
					callback && callback();
					uni.hideLoading();
				}
				break;
			case 1:
				// 1 开始
				if (type == 'loading') {
					// 开始显示loading
					uni.showLoading({ title, mask });
					// 需要一个超过多久时间自动结束的定时器
					if (timeout_callback) {
						setTimeout(() => {
							timeout_callback();
						}, timeout_limit);
					}
				} else if (type == 'msg') {
					_this.com_msg(title);
				} else if (type == 'none') {
				}
				break;
			case 2:
				// 2 成功
				if (title) {
					uni.showToast({ title, duration, icon });
				}
				if (callback) {
					if (hide_time > 0) {
						setTimeout(() => {
							callback && callback();
						}, hide_time);
					} else {
						callback && callback();
					}
				}
				break;
		}
		return true;
	},

	com_clearlist(e = {}) {
		let {
			load_name = 'loadingstatus',
			form_name = 'page_form',
			list_name = 'page_list',
			callback, //处理函数
		} = e;

		let _this = this;
		_this[load_name] = 0;
		if (_this.objJudge(_this[form_name]['limit'])) {
			_this[form_name].page = 1;
		}
		// _this[list_name] = [];
		callback && callback();
	},

	com_maxpage(e) {
		let { total, limit } = e;
		//计算最大页码
		let maxpage = parseInt(total / limit);
		if (total / limit - maxpage > 0) maxpage++;
		return maxpage;
	},
	// 通用提示
	com_msg(title, duration = 2000, mask = false, icon = 'none') {
		//统一提示方便全局修改
		if (Boolean(title) === false) {
			return;
		}
		uni.showToast({
			title,
			duration,
			mask,
			icon,
		});
	},
	// 返回上一页
	com_page_back(delta = 1, url = '') {
		let _this = this;
		if (url) {
			_this.goweburl_f(url, 2);
		} else {
			let routes = getCurrentPages();
			if (routes.length == 1) {
				_this.goweburl_f('/pages/index/index');
			} else {
				uni.navigateBack({
					delta,
				});
			}
		}
	},
	// 价格
	com_price(x) {
		if (!x) {
			x = 0;
		}
		var f = parseFloat(x);
		if (isNaN(f)) return false;
		var f = Math.round(x * 100) / 100;
		var s = f.toString();
		var rs = s.indexOf('.');
		if (rs < 0) {
			rs = s.length;
			s += '.';
		}
		while (s.length < rs + 1 + 2) {
			s += '0';
		}
		var leftNum = s.split('.')[0];
		var rightNum = '.' + s.split('.')[1];
		var result;
		var resultArray = new Array();
		if (leftNum.length > 3) {
			var i = true;
			while (i) {
				resultArray.push(leftNum.slice(-3));
				leftNum = leftNum.slice(0, leftNum.length - 3);
				if (leftNum.length < 4) {
					i = false;
				}
			}
			var sortArray = new Array();
			for (var i = resultArray.length - 1; i >= 0; i--) {
				sortArray.push(resultArray[i]);
			}
			result = leftNum + ',' + sortArray.join(',') + rightNum;
		} else {
			result = s;
		}
		return result;
	},
	// 数组排序
	com_sort_list(_list, key, mode) {
		// mode asc 正序 desc 倒序
		// 正序  [1, 3, 100]
		// 倒序 [100, 3, 1]

		// key 关键字段
		return _list.sort((p, n) => {
			let _p = isNaN(parseFloat(p[key])) ? 0 : parseFloat(p[key]);
			let _n = isNaN(parseFloat(n[key])) ? 0 : parseFloat(n[key]);
			if (mode == 'asc') {
				return _p < _n ? -1 : _p > _n ? 1 : 0;
			} else if (mode == 'desc') {
				return _p < _n ? 1 : _p > _n ? -1 : 0;
			}
		});
	},

	//  数组重组
	com_arr_classify(config) {
		let _this = this;
		let { _list, classify_key, classify_name = 'name', classify_list_name = 'list', o_fun = false, n_fun = false } = config;
		//  classify_key => 数组项中的key名筛选条件
		let check_shop = {};
		let i = 0;
		return _list.reduce((_p, _n) => {
			let _key = _n[classify_key];
			let o = {};
			if (!check_shop[_key]) {
				check_shop[_key] = {
					index: i,
				};

				// { name:classify_key ,list:[next,next,next,next]}

				o[classify_name] = _key;
				o[classify_list_name] = [];

				_p.push(o);
				i++;
			}
			_p[check_shop[_key].index][classify_list_name].push(_n);
			let can_fun = _this.objJudge(check_shop[_key]);
			if (o_fun && can_fun) {
				o = _p[check_shop[_key].index];
				_p[check_shop[_key].index] = o_fun(o);
			}
			// if (n_fun) {
			//     _n = n_fun(_n);
			// }
			// console.log(check_shop, 'check_shop')
			return _p;
		}, []);
		// [{ name:classify_key ,list:[next,next]},{ name:classify_key ,list:[next,next]}]
	},

	com_change_var(v, time = 0) {
		let _this = this;
		if (!this.nextreq) return;
		this[v] = !this[v];
		this.nextreq = false;
		if (time > 0) {
			setTimeout(() => {
				_this.nextreq = true;
			}, time);
		} else {
			_this.nextreq = true;
		}
	},

	com_modal(e = {}) {
		let { title = '', content = '确认执行该操作？', confirmText = '确认', cancelText = '取消', showCancel = true } = e;
		let _this = this;

		return new Promise((resolve, reject) => {
			let config = {
				confirmText,
				cancelText,
				showCancel,
				success(res) {
					if (res.confirm) {
						resolve(true);
					} else {
						resolve(false);
					}
				},
			};
			if (title) {
				config['title'] = title;
			}
			if (content) {
				config['content'] = content;
			}
			// console.log(config);
			uni.showModal(config);
		});
	},

	com_pagelogin_initcallback() {
		let _this = this;
		setTimeout(() => {
			_this.render_component_init = true;
		}, 300);
	},

	com_onshow_fun() {
		let _this = this;
		_this.change_var.page_canshow = true;
		let _caninit = true;
		if (_this.WORKING_PREVIEW_IMAGE) {
			// 查看完了
			_caninit = false;
			clearTimeout(COMMON_PUBLIC_TASK);
			COMMON_PUBLIC_TASK = setTimeout(() => {
				_this.store_set_state({ state_name: 'WORKING_PREVIEW_IMAGE', state_value: false });
			}, 1000);
		}
		if (!_this.render_component_init) _caninit = false;
		if (_this.WORKING_SCAN || _this.WORKING_PAY || _this.WORKING_SELECT_FILE) _caninit = false;
		if (_caninit) {
			_this.$refs.pagelogin.component_init();
		}
		// console.log(`${_this.change_var.page_canshow}--com_onshow_fun`);
	},

	com_page_hide(_this) {
		_this.change_var.page_canshow = false;
		_this.stop_scan();
		// console.log(_this.change_var.page_canshow);
		// console.log(_this.change_var);
		// console.log('com_page_hide');
		// console.log(`${_this.change_var.page_canshow}--隐藏页面`);
	},
	com_page_unload(_this) {
		_this.stop_scan();
		console.log('com_page_unload');
	},
	// 页面高度如果大于屏幕高度取默认值
	// 页面高度如果小于屏幕高度取 两者差值
	get_pageScrollTop_targe(config) {
		let _this = this;
		let targe = 0;
		let _default = config.scrollTop_targe;
		let _page = config.page_height - config.win_height;
		return _page > _default ? _default : _page;
	},
	get_view_info(config) {
		let _this = this;
		let { viewNmae, viewCallBack } = config;
		const query = uni.createSelectorQuery().in(_this);
		query.select(viewNmae)
			.boundingClientRect(data => {
				viewCallBack && viewCallBack(data);
			})
			.exec();
	},

	module_judge_render() {
		let _this = this;
		let refs = this.$refs;
		if (refs.pagelogin) {
			let filter_ref = ['diynav', 'mybtns']; // 需要进行运算的组件ref名
			let checks = {};
			let n = 0; //登录渲染前的异步数量
			let iname = '';
			let tname = '';
			for (const k in refs) {
				let item = refs[k];
				// console.log(k, 'k')
				if (filter_ref.indexOf(k) != -1) {
					tname += tname ? `,${k}` : k;
					_this.$set(checks, k, item);
					// checks[k] = item;
					// console.log(item.render, 'item')
					if (_this.objJudge(item.render) && item.render == 1) {
						n++;
						iname += iname ? `,${k}` : k;
					}
				}
			}
			// console.log(`组件渲染后回调--module_judge_render--加载完${n}个,${iname}，一共${Object.keys(checks).length}个,${tname}`)
			if (n == Object.keys(checks).length && _this.render_req == false) {
				//    执行登录组件初始化
				// console.log(refs['pagelogin'], ' refs')
				refs['pagelogin'].component_init();
			}
		}
	},
	rpxTopx(rpx) {
		return uni.upx2px(rpx);
	},
	pxTorpx(px) {
		const screenWidth = uni.getSystemInfoSync().screenWidth;
		let v = (750 * Number.parseInt(px)) / screenWidth;
		return parseFloat(v.toFixed(0));
	},
	back_number(v, w = 2) {
		let _this = this;
		let type = _this.gettype(v);

		if (type == 'String') {
			if (v == '--') {
				return '--';
			} else {
				return parseFloat(parseFloat(v).toFixed(w));
			}
		} else if (type == 'Number') {
			return parseFloat(v.toFixed(w));
		} else {
			return 0;
		}
	},
	back_fixed(v, w = 2) {
		return v.toFixed(w);
	},
	goweburl_f(url, tt = 0, title = '') {
		let _this = this;
		let _config = this.com_set_config();

		if (!_config.routerclick) {
			return false;
		}

		if (!url || url.length < 4) {
			return false;
		}
		_config.routerclick = false;
		url = url.trim();
		if (tt == 100) {
			_config.routerclick = true;

			if (url) {
				// this.getLiveInfo(url)
				this.goVideoIndex(url);
			}
		} else {
			if (url.substring(0, 4) == 'http') {
				// #ifdef APP-PLUS
				plus.runtime.openURL(url);
				_config.routerclick = true;
				// #endif

				// #ifdef MP
				uni.navigateTo({
					url: `/pages/index/goviews?path=${encodeURIComponent(url)}`,
					fail(res) {},
					complete() {
						_config.routerclick = true;
					},
				});
				// #endif
			} else if (url.substring(0, 1) == '/') {
				if (tt == 2) {
					uni.redirectTo({
						url: url,
						complete() {
							_config.routerclick = true;
						},
					});
				} else {
					uni.navigateTo({
						url: url,
						fail(res) {
							_config.routerclick = true;
							uni.switchTab({
								url: url,
								complete() {
									_config.routerclick = true;
								},
							});
						},
						complete() {
							_config.routerclick = true;
						},
					});
				}
			} else {
				_config.routerclick = true;
			}
		}

		if (title) {
			uni.setNavigationBarTitle({
				title: title,
			});
		}
	},

	fortprice(value = 0) {
		if (!value) {
			value = 0;
		}
		value = value * 1;
		if (isNaN(value)) return 0;
		return value.toFixed(2);
	},
	// 比较时间返回时间戳
	compare_time(start, end, mode = 'default') {
		// mode 默认显示 x年x月x天

		let sDate, eDate, sTime, eTime, diff, year, month, day, minute;
		let _back = null;
		// 开始时间
		if (start) {
			sDate = new Date(start);
		} else {
			sDate = new Date();
		}

		// 结束时间
		if (end) {
			eDate = new Date(end);
		} else {
			eDate = new Date();
		}

		sTime = sDate.getTime();
		eTime = eDate.getTime();

		// 相差的时间
		if (eTime > sTime) {
			diff = eTime - sTime;
		} else {
			return -1;
		}
		year = Math.floor(diff / (1000 * 60 * 60 * 24 * 365));
		month = Math.floor(diff / (1000 * 60 * 60 * 24 * 30));
		day = Math.floor(diff / (1000 * 60 * 60 * 24));

		if (mode == 'year') {
			_back = year;
		}
		if (mode == 'day') {
			_back = day;
		}

		if (mode == 'default') {
			_back = diff;
		}
		return _back;
	},
	// 比较限定时间 来重新定义执行回调事件的定时器.
	// 防止过快触发查询事件
	recurring_task_judge(config, callback = false, return_callback = false) {
		// need_diff 需要隔多久才执行回调
		let { cache_name, need_diff = 10000 } = config;
		// 取缓存条件时间进行计算 进行定时任务
		let _this = this;
		let task_config = uni.getStorageSync('task_config') || {};
		let cache_time = null;
		let now_time = new Date().getTime();
		let cache_diff = null;
		let fun_time = need_diff;
		if (_this.objJudge(task_config[cache_name])) {
			// 取上一次触发的时间
			cache_time = task_config[cache_name];
			// '2024-3-5 10:20:04', '2024-3-5 10:20:00'
			cache_diff = now_time - cache_time; // 4000
			// 10000, 4000
			if (need_diff > cache_diff) {
				fun_time = need_diff - cache_diff;
			} else {
				fun_time = 300;
			}
		} else {
			fun_time = 100;
		}
		console.log(_this.happenTimeFun(cache_time, 'y-m-d h:i:s'), cache_diff, fun_time);
		if (callback) {
			clearTimeout(_this.recurring_task);
			_this.recurring_task = setTimeout(() => {
				callback();
				task_config[cache_name] = new Date().getTime();
				uni.setStorageSync('task_config', task_config);
			}, fun_time);
		}

		if (return_callback) {
			if (fun_time > 300) {
				return_callback();
			}
		}
	},
	timeJudge(TIME_TARGET) {
		let _this = this;
		let _DATE = null;
		let _CONFIG = null;
		// 1字符串 2数字时间戳
		let IS_STRING = true;
		if (!_this.objJudge(TIME_TARGET)) return false;
		// 检查是否是数字
		if (typeof TIME_TARGET === 'number' && !isNaN(TIME_TARGET)) {
			// 检查是否在合理的时间范围内
			let isNum = TIME_TARGET >= 0 && TIME_TARGET < new Date().setFullYear(3000);
			if (isNum) {
				IS_STRING = false;
			}
		}
		if (IS_STRING == 1) {
			// 根据字符串初始化
			_DATE = new Date(TIME_TARGET);
			if (!_this.isValidDate(_DATE)) {
				TIME_TARGET = TIME_TARGET.replace(/T/g, ' '); //去掉T
				TIME_TARGET = TIME_TARGET.replace(/-/g, '/');
				TIME_TARGET = TIME_TARGET.replace(/\.\d+/, ' '); //去掉毫秒
				_DATE = new Date(TIME_TARGET);
			}
		} else {
			// 根据时间戳初始化
			_DATE = new Date(TIME_TARGET);
		}
		_CONFIG = {
			// 获取结束时间的年月日时分秒
			year: _DATE.getFullYear(),
			month: _DATE.getMonth() + 1,
			day: _DATE.getDate(),
			hour: _DATE.getHours(),
			minute: _DATE.getMinutes(),
			second: _DATE.getSeconds(),
			getTime: _DATE.getTime(),
		};
		return _CONFIG;
	},
	// 时间初始化 几秒前 几分钟前
	// 1分钟内 显示 '刚刚'
	// 60分钟内 显示 'xx分钟前'
	initAccurateTime(timer) {
		let _this = this,
			NOW_DATE,
			TARGET_DATE,
			NOW_TIME,
			NOW_YEAR,
			NOW_DAY,
			init_second = 1000,
			init_minute = init_second * 60,
			init_hour = init_minute * 60,
			init_day = init_hour * 24,
			diff_second,
			diff_minute,
			diff_hour,
			diff_day,
			DIFF,
			TEXT;
		NOW_DATE = new Date();
		TARGET_DATE = _this.timeJudge(timer);
		if (!TARGET_DATE) return;
		NOW_TIME = NOW_DATE.getTime();
		NOW_YEAR = NOW_DATE.getFullYear();
		NOW_DAY = NOW_DATE.getDate();

		let { year, month, day, hour, minute, second, getTime: TRAGET_TIME } = TARGET_DATE;
		let show_month = _this.append_zero(month);
		let show_day = _this.append_zero(day);
		let show_hour = _this.append_zero(hour);
		let show_minute = _this.append_zero(minute);

		DIFF = NOW_TIME - TRAGET_TIME;

		diff_day = Math.floor(DIFF / init_day);
		diff_hour = Math.floor(DIFF / init_hour);
		diff_minute = Math.floor(DIFF / init_minute);
		diff_second = Math.ceil(DIFF / init_second);
		// console.log(NOW_DAY, day);
		if (day + 1 == NOW_DAY) {
			// 昨天
			// console.log(DIFF, init_day, diff_day);
			TEXT = `昨天 ${show_hour}:${show_minute}`;
		} else if (diff_hour < 24 && diff_hour >= 1) {
			TEXT = `${diff_hour} 小时前`;
		} else if (diff_minute < 60 && diff_minute >= 1) {
			TEXT = `${diff_minute} 分钟前`;
		} else if (diff_second < 60 && diff_second >= 1) {
			// TEXT = `${diff_second}秒前`;
			TEXT = '刚刚';
		} else if (NOW_YEAR == year) {
			// 同一年 省略年份
			TEXT = `${show_month}-${show_day} ${show_hour}:${show_minute} `;
		} else if (NOW_YEAR != year) {
			TEXT = `${year}-${show_month}-${show_day} ${show_hour}:${show_minute} `;
		}
		// console.log(TEXT);
		// console.log({ diff_day, diff_hour, diff_minute, diff_second, DIFF });
		// console.log(TARGET_DATE);
		return TEXT;
	},

	append_zero(n) {
		return n >= 0 && n < 10 ? '0' + n : '' + n;
	},
	happenTimeFun(num, types = 'y-m-d h:i', dd = 1) {
		let _this = this;
		if (!num) {
			return '';
		}
		// 1字符串 2数字时间戳
		let num_type = 1;
		// 检查是否是数字
		if (typeof num === 'number' && !isNaN(num)) {
			// 检查是否在合理的时间范围内
			let isNum = num >= 0 && num < new Date().setFullYear(3000);
			if (isNum) {
				num_type = 2;
			} else {
				return;
			}
		}

		let zthisTime;
		let date;

		if (num_type == 1) {
			// 根据字符串初始化
			zthisTime = num + '+0800';
			date = new Date(zthisTime);

			if (!this.isValidDate(date)) {
				num = num.replace(/T/g, ' '); //去掉T
				num = num.replace(/-/g, '/');
				num = num.replace(/\.\d+/, ' '); //去掉毫秒
				date = new Date(num);
			}

			// zthisTime = num;
			// if (dd == 1) {

			//     if (_this.gettype(num) == 'String') {
			//         zthisTime = num.replace(/-/g, '/');

			//     }
			// }
			// date = new Date(zthisTime);
			// if (!this.isValidDate(date)) {
			//     date = new Date(num);
			// }
		} else {
			// 根据时间戳初始化
			date = new Date(num);
			// console.log(num)
			// console.log(date)
		}

		let y = date.getFullYear();
		let MM = date.getMonth() + 1;
		MM = MM < 10 ? '0' + MM : MM;
		let d = date.getDate();
		d = d < 10 ? '0' + d : d;
		let h = date.getHours();
		h = h < 10 ? '0' + h : h;
		let m = date.getMinutes();
		m = m < 10 ? '0' + m : m;
		let s = date.getSeconds();
		s = s < 10 ? '0' + s : s;

		if (types == 'y-m-d h:i:s') {
			return `${y}-${MM}-${d} ${h}:${m}:${s}`;
		} else if (types == 'y/m/d h:i:s') {
			return `${y}/${MM}/${d} ${h}:${m}:${s}`;
		} else if (types == 'h:i') {
			return h + ':' + m;
		} else if (types == 'y-m-d_text') {
			return `${y}年${MM}月${d}日`;
		} else if (types == 'y-m-d h:i') {
			return `${y}-${MM}-${d} ${h}:${m}`;
		} else if (types == 'y.MM.dd hh.i') {
			return `${y}.${MM}.${d} ${h}:${m}`;
		} else if (types == 'y-m-d') {
			return `${y}-${MM}-${d}`;
		} else if (types == 'y/MM/dd') {
			return `${y}/${MM}/${d}`;
		} else if (types == 'y') {
			return `${y}`;
		} else if (types == 'MM') {
			return `${MM}`;
		} else if (types == 'dd') {
			return `${d}`;
		} else if (types == 'h:i:s') {
			return h + ':' + m + ':' + s;
		} else if (types == 'ms') {
			return `${m}m ${s}s`;
		} else if (types == 'ms_txt') {
			return `${m}分${s}秒`;
		} else {
			return `${y}/${MM}/${d} ${h}:${m}`;
		}
	},

	// 时间戳转 年月日时分秒
	timestamp_show_fun(timing, types = 1) {
		let hour = Math.floor(timing / 1000 / 60 / 60);
		let minute = Math.floor((timing / 1000 / 60) % 60);
		let seconds = Math.floor((timing / 1000) % 60);
		let _back = null;
		switch (types) {
			case 1:
				_back = `${hour}H ${minute}m ${seconds}s`;
				break;
			case 2:
				_back = `${hour}小时${minute}分`;
				break;
		}

		return _back;
	},
	isValidDate(date) {
		return date instanceof Date && !isNaN(date.getTime());
	},

	startPulldownJudge(type) {
		let _this = this;
		if (type == 1) {
			_this.change_var.pulldown = 1;
			if (_this.objJudge(_this.$refs.paging)) {
			} else {
				_this['change_var']['repeat_once'] = true;
			}
		}
		_this.com_clearlist();
	},
	// 停止下拉刷新
	pulldownJudge() {
		let _this = this;
		if (_this.change_var.pulldown == 1) {
			_this.change_var.pulldown = 0;
			if (_this.objJudge(_this.$refs.paging)) {
				_this.$refs.paging.complete();
			}
			uni.stopPullDownRefresh();
		}
	},

	// 倒计时
	RemainTime(isend = false) {
		let _this = this;
		// _this.send_req = true;
		// console.log(_this.iTime, 'viTimeiTime')
		let iTime = _this.iTime,
			iTime_task = _this.iTime_task;
		let iSecond,
			sSecond = '',
			iMinute,
			sTime = '';

		if (iTime >= 0) {
			iSecond = parseInt(iTime % 60);
			iMinute = parseInt(iTime / 60);
			if (iSecond >= 0) {
				if (iMinute > 0) {
					sSecond = iMinute + '分' + iSecond + 'S';
				} else {
					sSecond = iSecond + 'S';
				}
			}
			sTime = sSecond;
			if (iTime <= 0) {
				clearTimeout(_this.iTime_task);
				_this.iTime_task = null;
				sTime = '重新发送';
				_this.iTime = _this.change_var.page_iTime;
				_this.send_req = true;
			} else {
				if (isend) {
					clearTimeout(_this.iTime_task);
					_this.iTime_task = null;
					_this.iTime = _this.change_var.page_iTime;
					sTime = '获取验证码';
				} else {
					_this.iTime_task = setTimeout(function () {
						_this.RemainTime();
					}, 1000);
					_this.iTime = iTime - 1;
				}
			}
		} else {
			sTime = '没有倒计时';
		}
		_this.code_tips = sTime;
	},

	//图片放大
	com_previewImage(config) {
		let _this = this;
		let { urls, current, key = false } = config;
		let urls_list = urls.reduce((p, n) => {
			let imgSrc = '';
			if (_this.objJudge(n[key]) && key) {
				imgSrc = n[key];
			} else if (_this.objJudge(n['image'])) {
				imgSrc = n['image'];
			} else {
				imgSrc = n;
			}
			p.push(imgSrc);
			return p;
		}, []);
		// console.log(current);
		// console.log(urls_list);
		uni.previewImage({
			urls: urls_list,
			current,
		});
	},
	// 匹配富文本的视频链接和图片链接
	mateVideoImage(html, split = ',') {
		let _this = this;
		let IMAGE = '';
		let VIDEO = '';
		let RICH_TEXT = '';
		let image_match = [...html.matchAll(/<img\s+src="([^"]+)"/g)];
		image_match.forEach(match => {
			IMAGE += IMAGE ? `${split}${match[1]}` : match[1];
		});
		let video_match = [...html.matchAll(/<source\s+src="([^"]+)"/g)];
		video_match.forEach(match => {
			VIDEO += VIDEO ? `${split}${match[1]}` : match[1];
		});

		RICH_TEXT = html.replace(/<div\s+data-w-e-type="video"[\s\S]*?<\/div>/g, '');
		RICH_TEXT = RICH_TEXT.replace(/<p><img[\s\S]*?\/><\/p>/g, '');

		// console.log(IMAGE, VIDEO, RICH_TEXT);
		return { IMAGE, VIDEO, RICH_TEXT };
	},

	formatRichText(html) {
		if (!html) {
			return '';
		}
		let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
			match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
			match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
			match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
			return match;
		});
		newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
			match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
			return match;
		});
		newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:inline-block;"');
		return newContent;
	},
	// 滚动到对应表单
	getscrollTop(what, _this) {
		const query = uni.createSelectorQuery().in(_this);
		query.select(what)
			.boundingClientRect(data => {
				let top = data.top + _this.pagescrollTop - _this.header_hight - 30;
				// if (top < 0) top = 0;
				console.log(data, what, top, '不通过2');
				uni.pageScrollTo({
					scrollTop: top,
					duration: 500,
				});
			})
			.exec();
		return false;
	},
	// 处理post数据
	get_post_data(obj, total_name = 'content') {
		let _this = this;
		let myinit = function (e) {
			let { obj, current_name, end_value, total_name, data, isend, islooping } = e;

			if (isend) {
				// 最后的节点了
				// total_name => 'content[con_float_electricity][el_fa_fee][0][key]' 递归拼接出来的字段名
				// end_value => 7  对应最后的值
				data[`${total_name}`] = end_value;
				// console.log({
				//     current_name,
				//     end_value,
				//     data,
				//     total_name,
				//     data,
				//     isend
				// });
			} else {
				// 还有下级 获取上此循环传入的total_name和current_name拼接

				if (islooping) total_name += current_name;

				let obj_type = Object.prototype.toString.call(obj).slice(8, -1);
				switch (obj_type) {
					case 'Undefined':
						myinit({
							current_name,
							end_value: obj,
							total_name,
							data,
							isend: true,
						});
						break;
					case 'Null':
						myinit({
							current_name,
							end_value: obj,
							total_name,
							data,
							isend: true,
						});
						break;
					case 'String':
						myinit({
							current_name,
							end_value: obj,
							total_name,
							data,
							isend: true,
						});
						break;
					case 'Number':
						myinit({
							current_name,
							end_value: obj,
							total_name,
							data,
							isend: true,
						});
						break;
					case 'Boolean':
						myinit({
							current_name,
							end_value: obj,
							total_name,
							data,
							isend: true,
						});
						break;
					case 'Array':
						if (obj.length == 0) {
							myinit({
								current_name,
								end_value: JSON.stringify(obj),
								total_name,
								data,
								isend: true,
							});
						} else {
							for (let i = 0; i < obj.length; i++) {
								myinit({
									obj: obj[i],
									current_name: `[${i}]`,
									end_value,
									total_name,
									data,
									isend,
									islooping: true,
								});
							}
						}
						break;
					case 'Object':
						if (!_this.objJudge(obj)) {
							myinit({
								current_name,
								end_value: JSON.stringify(obj),
								total_name,
								data,
								isend: true,
							});
						} else {
							for (let k in obj) {
								myinit({
									obj: obj[k],
									current_name: `[${k}]`,
									end_value,
									total_name,
									data,
									isend,
									islooping: true,
								});
							}
						}

						break;
				}
			}
			return data;
		};
		return myinit({
			obj,
			data: {},
			total_name,
			isend: false,
			islooping: false,
		});
	},

	// 校验表单项返回结果 true false
	// phone name
	page_check(v, check_v, k = 'nextreq') {
		let _this = this;

		let ele = _this.COMMON_VAR.page_check_config[check_v];

		if (!ele) return;
		let t_null = ele.tips_null;
		let t_fail = _this.objJudge(ele.tips_fail) ? ele.tips_fail : t_null;

		if (!v) {
			// 空提示
			_this.com_msg(t_null);
			_this[k] = true;
			return false;
		}
		let re_name = ele.regular;

		if (_this.objJudge(re_name)) {
			// 需要正则验证
			if (!_this[re_name].test(v)) {
				_this.com_msg(t_fail);
				_this[k] = true;
				return false;
			}
		}
		return true;
	},
	// 权限判断显示
	roleJudge(v) {
		let _this = this;
		let { user_status = 0 } = _this.USER_MSG;

		// 禁止查看
		let dis_show_config = {
			// 普通用户禁止查看压差 单串以及设置参数
			0: [
				'dev_diff',
				'index_voltage_chart',
				'current_calibration',
				'voltage_calibration',
				'reset_capacity',
				'initialize',
				'protection_parameters',
				'protection_count',
				'current_setting',
				'temperature_setting',
				'balanced_setting',
				'capacity_voltage_setting',
				'link_resistance',
				'function_setting',
				'system_setting',
			],
			// 管理员
			1: [],
			// 经销商 只能看
			2: [],
			// 特殊用户可以查看压差 单串以及设置参数
			4: [
				'current_calibration',
				'voltage_calibration',
				'reset_capacity',
				'initialize',
				'protection_parameters',
				'protection_count',
				'current_setting',
				'temperature_setting',
				'balanced_setting',
				'capacity_voltage_setting',
				'link_resistance',
				'function_setting',
				'system_setting',
			],
		};

		let my_config = dis_show_config[user_status];
		let key = v.key || v.form_key || v.view_type;
		// console.log(key);
		if (_this.objJudge(my_config)) {
			if (my_config.indexOf(key) > -1) {
				return false;
			} else {
				return true;
			}
		} else {
			return true;
		}
	},

	// 数据判空
	objJudge(obj) {
		let result = Object.prototype.toString.call(obj).slice(8, -1);
		// console.log(obj, result, 'objJudge')
		switch (result) {
			case 'Undefined':
				return false;
				break;
			case 'Null':
				return false;
				break;
			case 'Object':
				// return JSON.stringify(obj) !== '{}'
				return Object.keys(obj).length != 0;
				break;
			case 'Array':
				return obj.length !== 0;
				break;
			case 'ArrayBuffer':
				return obj.byteLength !== 0;
				break;
			case 'String':
				return obj !== '' && obj !== '--' && obj !== '-';
				// && obj !== '0'
				break;
			case 'Number':
				return true;
				break;
			case 'Boolean':
				return obj;
				break;
		}
	},

	gettype(obj) {
		let result = Object.prototype.toString.call(obj).slice(8, -1);
		if (result === 'Null') {
			return null;
		} else if (result === 'Undefined') {
			return undefined;
		} else {
			return result;
		}
	},
	deepclone(obj) {
		let warp;
		let _this = this;
		// 读取类型
		let objtype = _this.gettype(obj);
		if (objtype === 'Object') {
			warp = {};
		} else if (objtype === 'Array') {
			warp = [];
		} else {
			return obj;
		}
		for (let x in obj) {
			//  得到的数据内容
			let value = obj[x];
			if (_this.gettype(value) === 'Object' || _this.gettype(value) === 'Array') {
				warp[x] = _this.deepclone(value);
			} else {
				warp[x] = obj[x];
			}
		}
		return warp;
	},
	GET_LENGTH(DATA) {
		let _this = this;
		let TYPE = _this.gettype(DATA);
		let COUNT = 0;
		switch (TYPE) {
			case 'Object':
				COUNT = Object.keys(DATA).length;
				break;
			case 'Array':
				COUNT = DATA.length;
				break;
			case 'String':
				COUNT = DATA.length;
				break;
			case 'Number':
				COUNT = DATA.toString().length;
				break;
		}
		return COUNT;
	},

	// 十六进制色值转RGB #fff 或者 #ffffff   255,255,255
	hexadecimalToRgb(v) {
		let _this = this;
		let hexa_arr = v.substring(1).match(/.{1,2}/g);
		let t_arr = hexa_arr.map(item => {
			return _this.stt(item);
		});
		let hex = t_arr.join(',');
		return hex;
	},
	// 十六进制转十进制
	stt(vv, tt = 16) {
		return parseInt(vv, tt);
	},

	/**
	 * 十六进制转二进制数组
	 * @param {number} vv 十进制数字 1001
	 * @param {number} nn 数组长度 1byte对应8位  2byte对应16位
	 * @returns Array
	 */
	sttwo(vv, nn = 16, end = true) {
		let _data = this.tts(vv);
		var bitsArray = new Array(nn);
		for (var i = 0; i < nn; i++) {
			if (end) {
				// 高位在后 13 -> 1011
				bitsArray[i] = (_data >> i) & 1;
			} else {
				// 高位在前 13 -> 1101
				bitsArray[nn - 1 - i] = (_data >> i) & 1;
			}
		}
		return bitsArray;
	},
};
